package cmdb

import (
	"github.com/gin-gonic/gin"
	"k8s-platform/model"
	"k8s-platform/service/cmdb"
	"net/http"
)

var Credential credential

type credential struct{}

// 新增
func (*credential) Add(c *gin.Context) {
	p := &model.Credential{}
	if err := c.ShouldBindJSON(p); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90400,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	if err := cmdb.Credential.Add(p); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "创建credential成功",
		"data": nil,
	})
}

// 查看列表
func (*credential) List(c *gin.Context) {
	data, err := cmdb.Credential.List()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "查询credential列表成功",
		"data": data,
	})
}

// 查看Credential详情
func (*credential) GetDetail(c *gin.Context) {
	p := new(struct {
		ID int64 `form:"id"`
	})
	if err := c.Bind(p); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90400,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	data, _, err := cmdb.Credential.Get(p.ID)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "查询Credential详情成功",
		"data": data,
	})
}

// 更新credential
func (*credential) Update(c *gin.Context) {
	p := &model.Credential{}
	if err := c.ShouldBindJSON(p); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90400,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	if err := cmdb.Credential.Update(p); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "更新Credential成功",
		"data": nil,
	})
}

// 删除credential
func (*credential) Delete(c *gin.Context) {
	p := &model.Credential{}
	if err := c.ShouldBindJSON(p); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90400,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	if err := cmdb.Credential.Delete(p, p.ID); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 90500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "删除credential成功",
		"data": nil,
	})
}
